from App001.utils.bootstrap import BootStrapModelForm  #引入自身的Bootstrap
from django.shortcuts import render, HttpResponse, redirect
from django.views.decorators.csrf import csrf_exempt #进行密码校验
from App001 import models
from django.http import JsonResponse
import random
from datetime import datetime
from django import forms
import json


class OrderModelForm(BootStrapModelForm):
    class Meta:
        model = models.Order
        # fields ="__all__"
        exclude = ["oid", "admin"] #排除这俩，让其不显示


def order_list(request):
    queryset = models.Order.objects.all()
    form = OrderModelForm()
    context = {
        "form": form,
        "queryset": queryset
    }
    return render(request, 'order_list.html', context)


@csrf_exempt
def order_add(request):
    """新建订单"""
    form = OrderModelForm(data=request.POST)
    if form.is_valid():
        # 下面的那个是自动生成的数然后填充进去的数值
        form.instance.oid = datetime.now().strftime("%Y%m%d%H%M%S") + str(random.randint(0, 99))
        # 去找到登录的这个账户的管理员，然后来进行控制
        form.instance.admin_id = request.session["info"]["id"]
        form.save()
        # data_dict = {"status": True}
        # return HttpResponse(json.dumps(data_dict))
        return JsonResponse({"status": True})

    # print()
    # data_dict = {"status": False, "error": form.errors}
    # return HttpResponse(json.dumps(data_dict, ensure_ascii=False))
    return JsonResponse({"status": True, "error": form.errors})


def order_delete(request):
    """删除订单"""
    uid = request.GET.get("uid")
    exists = models.Order.objects.filter(id=uid).exists()

    if not exists:
        return JsonResponse({"status": False, 'error': "获取失败,数据不存在"})
    models.Order.objects.filter(id=uid).delete()
    return JsonResponse({"status": True})


def order_detail(request):
    """
    uid = request.GET.get("uid")
    row_object = models.Order.objects.filter(id=uid).first()
    if not row_object:
        return JsonResponse({"status": False, 'error': "数据不存在"})

    result = {
        "status": True,
        "data": {
            "title": row_object.titile,
            "price": row_object.price,
            "status": row_object.status,
        }
    }
    return JsonResponse(result)

    下面使用第二种方式会更的简单的
"""
    uid = request.GET.get("uid")
    row_dict = models.Order.objects.filter(id=uid).values("title","price","status").first()
    if not  row_dict:
        return JsonResponse({"status": False, 'error': "数据不存在"})

    result = {
        "status": True,
        "data": row_dict
    }
    return JsonResponse(result)

@csrf_exempt
def order_edit(request):
    """编辑页面"""
    uid=request.GET.get("uid")
    row_object=models.Order.objects.filter(id=uid).first()
    if not row_object:
        return JsonResponse({"status": False, 'tips': "数据不存在"})
    form=OrderModelForm(data=request.POST,instance=row_object)
    if form.is_valid():
        form.save()
        return JsonResponse({"status": True})
    return JsonResponse({"status": True, "error": form.errors})
